using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Ink;
using System.Collections;
using Microsoft.Xna.Framework.Input;

namespace Pavilion.DesignerTool
{
    public class TabletInput
    {
        public event Action TabletReleased;
        public event Action<System.Windows.Point> TabletPressed, TabletRubbed;

        public System.Windows.Point CurrentPosition { get; private set; }
        public int Pressure { get; private set; }
        public float PressurePercentage { get { return (float)Pressure / MaxPressure; } }
        public int MaxPressure { get { return 32767; } }

        private InkCollector tabletInputCollector;
        private bool isRubbing;
        private System.Windows.Forms.Control control;

        public TabletInput(System.Windows.Forms.Control control)
        {
            this.control = control;
            tabletInputCollector = new InkCollector(this.control.Handle, false);

            ArrayList propList = new ArrayList(tabletInputCollector.DesiredPacketDescription);
            tabletInputCollector.DesiredPacketDescription = (Guid[])propList.ToArray(typeof(Guid));
            tabletInputCollector.Enabled = true;

            Pressure = MaxPressure / 2;

            tabletInputCollector.NewPackets += (object sender, InkCollectorNewPacketsEventArgs e) =>
            {
                Pressure = e.PacketData[e.PacketData.Length - 1];

                System.Drawing.Point penPosition = new System.Drawing.Point(e.PacketData[0], e.PacketData[1]);
                tabletInputCollector.Renderer.InkSpaceToPixel(control.CreateGraphics(), ref penPosition);
                CurrentPosition = new System.Windows.Point(penPosition.X, penPosition.Y);

                if (!isRubbing)
                    OnTabletPressed(CurrentPosition);
                else
                    OnTabletRubbed(CurrentPosition);
            };

            tabletInputCollector.Stroke += (object sender, InkCollectorStrokeEventArgs e) => { OnTabletReleased(); };
        }

        private void OnTabletPressed(System.Windows.Point position)
        {
            isRubbing = true;

            if (TabletPressed != null)
                TabletPressed(position);
        }

        private void OnTabletReleased()
        {
            isRubbing = false;

            if (TabletReleased != null)
                TabletReleased();
        }

        private void OnTabletRubbed(System.Windows.Point position)
        {
            if (TabletRubbed != null)
                TabletRubbed(position);
        }
    }
}
